//
//  YWModifyNoticeTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/10/14.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWModifyNoticeTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "MBProgressHUD.h"

#import "YWPatrolPicture.h"
//#import "YWImageView.h"
#import "YWPhotoView.h"
#import "YWTextFieldCell.h"
#import "YWWriteNoteCell.h"
#import "YWTakePhotoCell.h"

#import "YWContactManager.h"
#import "YWDepartment.h"
#import "YWNoticeManager.h"
#import "YWKeepWatchMissionManager.h"
#import "YWNotice.h"

@interface YWModifyNoticeTableViewController ()
<YWWriteNoteCellDelegate,YWTakePhotoCellDelegate,YWTextFieldCellDelegate>{
    NSString *noticeTitle;
    NSString *noticeContent;
}

@property (nonatomic, strong) NSArray *totalImageNameArray;
@property (nonatomic, strong) NSArray *departmentArray;
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) UIView *footView;
@end

@implementation YWModifyNoticeTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"modifyNotice", nil);//@"修改通知";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", nil) style:UIBarButtonItemStylePlain target:self action:@selector(clickCancelBarButtonEvent:)];
    
    [self stupData];
    [self initTableView];
}

- (void)stupData{
    noticeTitle = self.notice.title;
    noticeContent = self.notice.content;
    NSArray *pictures = [[YWKeepWatchMissionManager shareManager]recordPictureWithRecordId:[NSString stringWithFormat:@"%ld",(long)self.notice.noticeId] recordType:YWPictureRecordTypeNotice];
    self.totalImageNameArray = pictures?:nil;
}

- (void)initTableView{
    [self.tableView registerClass:[YWTextFieldCell class] forCellReuseIdentifier:YWTextFieldCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWTakePhotoCell class] forCellReuseIdentifier:YWTakePhotoCellIdentifier];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0) {
        return 44;
    }else if (indexPath.section == 1){
        return 44;
    }else if (indexPath.section == 2){
        return 90;
    }else if (indexPath.section == 3){
        CGFloat imageH = YWPhotoSize*(self.totalImageNameArray.count/4+1) + YWPhotoGap*(self.totalImageNameArray.count/4);
        return 10*2 + imageH;
    }else{
        return 0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return self.departmentArray.count;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        YWTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTextFieldCellIdentifier];
        cell.delegate = self;
        cell.textFieldContent = noticeTitle;
        cell.textFieldPlaceholder = NSLocalizedString(@"pleaseEnterTheTitle", nil);//@"请输入标题";
        return cell;
    }else if (indexPath.section == 1){
        static NSString *cellIdentifier = @"YWModifyNoticeTableVCReuseCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.font = kContentFont;
        }
        cell.textLabel.text = self.departmentArray[indexPath.row];
        return cell;
    }else if (indexPath.section == 2){
        YWWriteNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.textViewPlaceHolder = NSLocalizedString(@"pleaseEnterTheContent", nil);//@"请输入内容";
        cell.textViewContent = noticeContent;
        cell.delegate = self;
        return cell;
    }else{
        YWTakePhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTakePhotoCellIdentifier];
        cell.delegate = self;
        cell.pickFromPhotoLibrary = YES;
        cell.totalImageNameArray = self.totalImageNameArray;
        return cell;
    }
}

#pragma mark -- tableView section title

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWModifyNoticeTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return NSLocalizedString(@"titleOfNotice", nil);//@"通知标题";
    }else if (section==1){
        return NSLocalizedString(@"rangeOfNotice", nil);//@"通知范围（默认通知所有部门）";
    }else if (section==2){
        return NSLocalizedString(@"contentOfNotice", nil);//@"通知内容";
    }else if (section==3){
        return NSLocalizedString(@"addOrModifyPhotos", nil);//@"添加/修改图片";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

#pragma mark - YWTakePhotoCellDelegate
- (void)resetCellFrameWithImages:(NSArray *)images cell:(UITableViewCell *)cell{
    NSArray* arr = [[NSArray alloc] initWithArray:images];
    self.totalImageNameArray = arr;
    [self.tableView reloadData];
}

#pragma mark - YWTextFieldCellDelegate
- (void)passTextFieldContent:(NSString *)content cell:(UITableViewCell *)cell{
    //标题
    noticeTitle = content;
}

#pragma mark - YWWriteNoteCellDelegate
- (void)passNote:(NSString *)note{
    noticeContent = note;
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+30*2);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH-20*2;
        
        UIButton *button = [[UIButton alloc] init];
        button.clipsToBounds = YES;
        button.layer.cornerRadius = 4.0;
        button.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        [button setTitle:NSLocalizedString(@"send", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickSenderButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:button];
    }
    return _footView;
}

- (void)clickSenderButtonEvent:(id)sender{
    if (noticeTitle.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseEnterTheTitle", nil)];
        return;
    }
    if (noticeTitle.length>50) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"theLengthOfTitleMustBeLessThan50", nil)];
        return;
    }
    if ([YWCommonTool isContainsEmoji:noticeTitle]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (noticeContent.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseEnterTheContent", nil)];
        return;
    }
    if (noticeContent.length>500) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"theLengthOfContentMustBeLessThan500", nil)];
        return;
    }
    if ([YWCommonTool isContainsEmoji:noticeContent]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    //点击发送
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"makeSureToModifyNotice", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        [self postNotice];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)postNotice{
    NSArray *needUploadPictures = [self picturesNeedUpload:YES];
    NSArray *uploadedPictures = [self picturesNeedUpload:NO];
    
    _notice.title = noticeTitle;
    _notice.content = noticeContent;
    [[YWNoticeManager shareManager] modifyNoticeWithNotice:_notice needUploadPic:needUploadPictures uploadedPic:uploadedPictures WithComplete:^(BOOL success) {
        [self.HUD hide:YES];
        if (success) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"modifySucceed", nil)];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}
- (NSArray*)picturesNeedUpload:(BOOL)needUpload
{
    NSMutableArray* needpictures = [NSMutableArray array];
    for (int i = 0; i < [self.totalImageNameArray count]; i++) {
        id pic = self.totalImageNameArray[i];
        if (needUpload && [pic isKindOfClass:[NSString class]]) {
            YWPatrolPicture* picture = [[YWPatrolPicture alloc] init];
            picture.recordId = [YWCommonTool randStringId];
            picture.pictureId = [YWCommonTool randStringId];
            picture.pictureName = self.totalImageNameArray[i];
            picture.isLocalImage = YES;
            picture.uploadStatus = YWPictureRecordUploadStatusNull;
            picture.recordType = YWPictureRecordTypeNotice;
            [needpictures addObject:picture];
        }else if (!needUpload && [pic isKindOfClass:[YWPatrolPicture class]]){
            [needpictures addObject:pic];
        }
    }
    return needpictures;
}

- (NSArray *)departmentArray{
    if (!_departmentArray) {
        _departmentArray = [NSArray array];
        _departmentArray = [self.notice.receivers componentsSeparatedByString:@","];
    }
    return _departmentArray;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)clickCancelBarButtonEvent:(id)sender{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"quitEditing", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

@end
